import type { Station } from "@/common/types/interface";
import { TIMEOUT } from "./const";

export const showHistories = () => {
    uni.navigateTo({ url: '/pages/histories/histories' })
}
export const showFavotites = () => {
    uni.navigateTo({
        url: '/pages/favotites/favotites'
    })
}

/**
 * 显示完整播放器
 */
export const showFullPlayer = async () => {
    return uni.navigateTo({
        url: '/pages/fullPlayer/fullPlayer'
    })
};

export const queryStations = async (
    type: 'search' | 'lang' | 'tags',
    params: any,
    page: number,
    pageSize: number
): Promise<Station[]> => {
    const allStations = new Map<string, Station>();

    if (type === 'search') {
        const res = await uni.request({
            url: 'https://de1.api.radio-browser.info/json/stations/search',
            method: 'GET',
            data: {
                hidebroken: true,
                name: params.keyword,
                offset: (page - 1) * pageSize,
                limit: pageSize
            }
        });
        (res.data as Station[]).forEach(s => allStations.set(s.stationuuid, s));
    }

    else if (type === 'lang') {
        const res = await uni.request({
            url: `https://de1.api.radio-browser.info/json/stations/bylanguage/${params.lang}`,
            method: 'GET',
            data: {
                hidebroken: true,
                order: 'clickcount',
                offset: (page - 1) * pageSize,
                limit: pageSize
            }
        });
        (res.data as Station[]).forEach(s => allStations.set(s.stationuuid, s));
    }

    else if (type === 'tags') {
        const requests = params.tags.map((tag: string) =>
            uni.request({
                url: `https://de1.api.radio-browser.info/json/stations/bytag/${tag}`,
                method: 'GET',
                data: {
                    hidebroken: true,
                    order: 'clickcount',
                    offset: (page - 1) * pageSize,
                    limit: pageSize
                }
            })
        );

        // 并发执行请求
        const results = await Promise.all(requests);
        for (const res of results) {
            for (const station of res.data as Station[]) {
                allStations.set(station.stationuuid, station); // 去重
            }
        }
    }

    return Array.from(allStations.values());
};

export const getRandomStations = async (limit = 4) => {
    const res = await uni.request({
        url: 'https://de1.api.radio-browser.info/json/stations',
        method: 'GET',
        data: {
            hidebroken: true,
            order: 'random',
            limit: limit,
            t: Date.now()
        },
        timeout: TIMEOUT
    });
    return res.data as Station[];
}